"""
在线词典 ： 服务端数据处理
"""
import pymysql
import hashlib


# 密码进行哈希加密处理
class HashEncryption:
    def __init__(self):
        pass

    def sha512(self, passwd):
        # 固定盐
        hash = hashlib.sha512(b"*#06#")
        hash.update(passwd.encode())
        return hash.hexdigest()


# 数据库处理类
class DictData:
    def __init__(self):
        self.kwargs = {
            "user": "xiaogan",
            "password": "123456",
            "database": "dict",
            "charset": "utf8"
        }
        self.db = pymysql.connect(**self.kwargs)
        self.cur = self.db.cursor()
        self.encryption = HashEncryption()

    def close(self):
        self.cur.close()
        self.db.close()

    # 完成数据库注册用户插入
    def register(self, name, passwd):
        sql = "insert into user (user,password) values (%s,%s);"
        passwd = self.encryption.sha512(passwd)  # 密码转换
        try:
            self.cur.execute(sql, [name, passwd])
            self.db.commit()
            return True
        except Exception as e:
            print(e)
            self.db.rollback()

    # 验证是否可以登录
    def login(self, name, passwd):
        passwd = self.encryption.sha512(passwd)  # 密码转换
        sql = "select id from user where binary user=%s and password=%s;"
        self.cur.execute(sql, [name, passwd])
        return self.cur.fetchone()  # (id,) None

    # 查询单词
    def query(self, word):
        sql = "select id,mean from words where word=%s;"
        self.cur.execute(sql, [word])
        return self.cur.fetchone()  # (id,mean) None

    # 　插入历史记录
    def insert_hist(self, user_id, words_id):
        # user_id  words_id
        sql = "insert into hist (user_id,words_id) values (%s,%s);"
        try:
            self.cur.execute(sql, [user_id, words_id])
            self.db.commit()
        except:
            self.db.rollback()

    # 查询历史记录
    def hist(self, user_id):
        # 需要：name  word  time
        sql = "select user,word,time from " \
              "user inner join hist " \
              "on user.id=hist.user_id " \
              "inner join words " \
              "on words.id=hist.words_id " \
              "where user_id=%s " \
              "order by time desc " \
              "limit 10;"
        self.cur.execute(sql, [user_id])
        return self.cur.fetchall()  # ((),...) ()
